//
//  WTGiftAnimationManager.m
//  66TV
//
//  Created by ben on 16/8/4.
//  Copyright © 2016年 shifeng. All rights reserved.
//

#import "WTGiftAnimationManager.h"
#import <CommonCrypto/CommonDigest.h>



@interface WTGiftAnimationManager ()
/// 队列1
@property (nonatomic,strong) NSOperationQueue *queue1;
/// 队列2
@property (nonatomic,strong) NSOperationQueue *queue2;
/// 队列3
@property (nonatomic,strong) NSOperationQueue *queue3;

/// 操作缓存池
@property (nonatomic,strong) NSMutableDictionary *operationCache;
/// 维护用户礼物信息
@property (nonatomic,strong) NSMutableDictionary *userGiftInfos;

@end


@implementation WTGiftAnimationManager

+ (instancetype)sharedManager{
    
    static WTGiftAnimationManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[WTGiftAnimationManager alloc] init];
        
    });
    return manager;
}

- (void)clear{
    [self.operationCache removeAllObjects];
    [self.queue1 cancelAllOperations];
    [self.queue2 cancelAllOperations];
    [self.queue3 cancelAllOperations];
    [self.userGiftInfos removeAllObjects];
}

- (NSString *)cacheKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                          r[11], r[12], r[13], r[14], r[15], [[key pathExtension] isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", [key pathExtension]]];
    
    return filename;
}


- (void)animate:(NSString*)userID giftID:(NSString*)giftID giftModel:(WTChatRoomGiftModel*)giftModel finishedBlock:(void(^)(BOOL result,WTChatRoomGiftModel* giftModel,NSInteger count))finishedBlock{
    

    long long markQueueCount = [userID longLongValue];
    NSString* cacheKey = [self cacheKey:[NSString stringWithFormat:@"%@%@%zd",userID,giftID,giftModel.gift_count]];
    
    WTAnimationOperation* operation = [self.operationCache objectForKey:cacheKey];
    if(operation){
        operation.giftShowView.giftModel = giftModel;
        [operation.giftShowView shakeNumberLabel];
        
        return;
    }


    operation = [WTAnimationOperation animOperation:giftModel finishedBlock:^(BOOL result, NSInteger finishCount) {
        
        // 将礼物信息数量存起来
        [self.userGiftInfos setObject:@(finishCount) forKey:cacheKey];
        // 动画完成之后,要移除动画对应的操作
        [self.operationCache removeObjectForKey:cacheKey];
        
        // 延时删除用户礼物信息
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.userGiftInfos removeObjectForKey:cacheKey];
            
            if (finishedBlock) {
                finishedBlock(result,giftModel,finishCount);
            }
        });
    }];

    
    NSInteger count = [[self.userGiftInfos objectForKey:cacheKey] integerValue];
    if(count > 0){
        giftModel.gift_count = count + giftModel.gift_count;
    }

    operation.giftShowView = [[WTGiftShowView alloc] init];
    operation.giftContainerView = self.giftContainerView;
    operation.cacheKey = cacheKey;
    
    // 将操作添加到缓存池
    [self.operationCache setObject:operation forKey:cacheKey];
    
    NSInteger index = [self operationQueueIndex:markQueueCount % 3];
    operation.giftShowView.frame = CGRectMake(-CGRectGetWidth(self.giftContainerView.bounds) / 2, CGRectGetHeight(self.giftContainerView.bounds) -  (40) * (index + 1), CGRectGetWidth(self.giftContainerView.bounds), 30);
    
    if(index == 0){
        [self.queue1 addOperation:operation];
    }else if(index == 1){
        [self.queue2 addOperation:operation];
    }else {
        [self.queue3 addOperation:operation];
    }
}

- (NSInteger)operationQueueIndex:(NSInteger)index{
    
    if(index == 0){
        if(self.queue1.operationCount <= 0){
            return 0;
        }
        if(self.queue2.operationCount <= 0){
            return 1;
        }
        if(self.queue3.operationCount <= 0){
            return 2;
        }
    }else if(index == 1){
        if(self.queue2.operationCount <= 0){
            return 1;
        }
        if(self.queue1.operationCount <= 0){
            return 0;
        }
        if(self.queue3.operationCount <= 0){
            return 2;
        }
    }else {
        if(self.queue3.operationCount <= 0){
            return 2;
        }
        if(self.queue1.operationCount <= 0){
            return 0;
        }
        if(self.queue2.operationCount <= 0){
            return 1;
        }
    }
    return 0;
}


#pragma mark - getter
- (NSOperationQueue *)queue1{
    
    if (_queue1 == nil) {
        _queue1 = [[NSOperationQueue alloc] init];
        _queue1.maxConcurrentOperationCount = 1;
    }
    return _queue1;
}

- (NSOperationQueue *)queue2{
    
    if (_queue2 == nil) {
        _queue2 = [[NSOperationQueue alloc] init];
        _queue2.maxConcurrentOperationCount = 1;
    }
    return _queue2;
}

- (NSOperationQueue *)queue3{
    
    if (_queue3 == nil) {
        _queue3 = [[NSOperationQueue alloc] init];
        _queue3.maxConcurrentOperationCount = 1;
    }
    return _queue3;
}

- (NSMutableDictionary *)operationCache{
    
    if (_operationCache==nil) {
        _operationCache = [[NSMutableDictionary alloc] init];
    }
    return _operationCache;
}

-(NSMutableDictionary *)NSMutableDictionary{
    if (_userGiftInfos == nil) {
        _userGiftInfos = [[NSMutableDictionary alloc] init];
    }
    return _userGiftInfos;
}

@end
